<?php

namespace app\admin\controller\orders;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\Session;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Shared_Date;
use PHPExcel_Style;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use PHPExcel_Style_NumberFormat;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Orders extends Backend
{
    
    /**
     * Orders模型对象
     * @var \app\admin\model\Orders
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Orders;
        $this->view->assign("payStyleList", $this->model->getPayStyleList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $shop_id=Session::get('admin.id');
          //  $shop_id=58;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with('users')
                ->where($where)
                ->where(['shop_id'=>$shop_id])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['users'=>function($query) {
                    $query->withField("phone,truename");
                }])
                ->where($where)
                ->where(['shop_id'=>$shop_id])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 订单详情
     */
    public function detail(){
        $this->request->filter(['strip_tags']);
        $param = $this->request->param();
        $field='g.id,d.goods_name,g.goods_image,d.num,g.goods_price,d.createtime';
        $detail = Db::connect('database.cheat')->name('orderinfo')
            ->alias('d')
            ->join('goods g','g.id=d.goods_id','LEFT')
            ->where(['d.son_order_id'=>['in',$param['ids']]])
            ->field($field)
            ->select();
      /*  foreach ($detail as $k=>$v){
            $detail[$k]['goods_image']=SHOPURL.$v['goods_image'];
        }*/
        $this->assign('detail', $detail);
        return $this->view->fetch();
    }
    /**
     * 发货
     */
    public function fh($ids){
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill)
                {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try
                {
                    $data['logistics_code']=$params['logistics_code'];  //订单号
                    $data['logistics']=$params['logistics'];    //物流
                    $data['status']=3;
                    $ins=Db::connect('database.cheat')->name('orders')->where(['id'=>$ids,'status'=>2])->update($data);
                    if (!$ins){
                        throw new Exception('发货失败');
                    }
                    $this->success('发货成功');
                }catch (Exception $e)
                {
                    $this->error($e->getMessage());
                }
                $this->success('发货成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 导出
     */
    public function export(){
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');
            $excel = new PHPExcel();
            $excel->getProperties()
                ->setCreator("FastAdmin")
                ->setLastModifiedBy("FastAdmin")
                ->setTitle("标题")
                ->setSubject("Subject");
            $excel->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $excel->getDefaultStyle()->getFont()->setSize(12);
            $this->sharedStyle = new PHPExcel_Style();
            $this->sharedStyle->applyFromArray(
                array(
                    'fill'      => array(
                        'type'  => PHPExcel_Style_Fill::FILL_SOLID,
                        'color' => array('rgb' => '000000')
                    ),
                    'font'      => array(
                        'color' => array('rgb' => "000000"),
                    ),
                    'alignment' => array(
                        'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
                        'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
                        'indent'     => 1
                    ),
                    'borders'   => array(
                        'allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN),
                    )
                ));

            $worksheet = $excel->setActiveSheetIndex(0);
            $worksheet->setTitle('标题');

//            $whereIds = $ids == 'all' ? '1=1' : ['o.id' => ['in', explode(',', $ids)]];
            $whereIds = $ids == 'all' ? ['o.shop_id'=>Session::get('admin.id')] : ['o.id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $columns_a=explode(',',$columns);
//            array_pop($columns_a);
//            array_shift($columns_a);
//            $columns=implode(',',$columns_a);
            $list=Db::connect('database.cheat')->name('orders')
                ->alias('o')
//                ->join('users users','orders.user_id=users.id','LEFT')
                ->join('orderinfo d','o.id=d.son_order_id','LEFT')
//                ->join('goods g','d.good_id=g.id','LEFT')
                ->field('o.id,d.goods_name,d.goods_price,d.num,o.order_num,o.total_money,o.pament_time,o.createtime,o.status,o.pay_style,o.names,o.phone,o.address,o.logistics,o.logistics_code')
                ->where($whereIds)
                ->where($where)
                ->select();
            if (empty($list)){
                $this->error('当前没有可以导出的订单','/admin/orders/orders?ref=addtabs');
            }
            foreach ($list as $k => $v) {
                $res[$v['order_num']]['son_order_id'] = $v['id'];
                $res[$v['order_num']]['order_num'] = ' '.$v['order_num'];
                $res[$v['order_num']]['logistics_code'] = ' '.$v['logistics_code'];
                $res[$v['order_num']]['logistics'] =$v['logistics'];
                $res[$v['order_num']]['status'] = $this->model->getStatusList()[$v['status']];
                $res[$v['order_num']]['names'] = $v['names'];
                $res[$v['order_num']]['pay_style'] =$this->model->getPayStyleList()[$v['pay_style']];
                $res[$v['order_num']]['phone'] = $v['phone'];
                $res[$v['order_num']]['total_money'] = $v['total_money'];
                $res[$v['order_num']]['address'] = $v['address'];
                $res[$v['order_num']]['goods_price'] = $v['goods_price'];
                $res[$v['order_num']]['pament_time'] = $v['pament_time'];
                $res[$v['order_num']]['createtime'] = $v['createtime'];
                $res[$v['order_num']]['goods'][$k] = '商品名称：'.$v['goods_name'].'  商品单价：'.$v['goods_price'].'  商品数量：'.$v['num'];
            }
            $res=array_values($res);
            $data = [];
            $data[0] = [
                'id'=>'序号','order_num'=>'订单编号','names'=>'收货人',
                'phone'=>'联系方式','address'=>'收货地址','total_money'=>'订单金额',
                'status'=>'订单状态','goods'=>'购买商品',
                'pay_style' =>'支付方式',
                'createtime'=>'下单时间','pament_time'=>'支付时间','logistics_code'=>'物流号','logistics'=>'物流公司'
            ];
            foreach ($res as $kk=>$vv){
                $data[$kk+1]['id']=$vv['son_order_id'];
                $data[$kk+1]['order_num']=$vv['order_num'];
                $data[$kk+1]['names']=$vv['names'];
                $data[$kk+1]['phone']=$vv['phone'];
                $data[$kk+1]['address']=$vv['address'];
                $data[$kk+1]['total_money']=$vv['total_money'];
                $data[$kk+1]['status']=$vv['status'];
                $data[$kk+1]['goods']=implode(',',$vv['goods']);
                $data[$kk+1]['pay_style']=$vv['pay_style'];
                $data[$kk+1]['createtime']=$vv['createtime'];
                $data[$kk+1]['pament_time']=$vv['pament_time'];
                $data[$kk+1]['logistics_code']=$vv['logistics_code'];
                $data[$kk+1]['logistics']=$vv['logistics'];
            }
            $this->put_excel("订单列表",$data);
            $this->success('导出成功');
        }
    }
    /**
     * 把数据写入一个文件
     * @param string $file 文件名
     * @param array|generator $data 数据，可以被 foreach 遍历的数据，数组或者生成器
     * @param string $tplFile 模板文件，以哪个模板填写数据，如果不提供则生成空白 xlsx 文件
     * @param int $skipRow 跳过表头的行数，默认为 1
     */
    function putExcel( $file, $data, $tplFile = null, $skipRow = 1 )
    {
        Vendor( "PHPExcel.PHPExcel" );
        if ( $tplFile ) {
            if ( file_exists( $tplFile ) ) {
                $objReader = \PHPExcel_IOFactory::createReader( 'Excel2007' );
                $objPHPExcel = $objReader->load( $tplFile );
            } else {
                throw new \Exception( "File `{$tplFile}` not exists" );
            }
        } else {
            $objPHPExcel = new \PHPExcel();
        }
        $objPHPExcel->setActiveSheetIndex( 0 );
        $objSheet = $objPHPExcel->getActiveSheet();
        $objSheet->setTitle( 'export' );
        $rowNum = 1;
        foreach ( $data as $row ) {
            $colNum = 0;
            foreach ( $row as $val ) {
                $objSheet->setCellValueByColumnAndRow(
                    $colNum,
                    $rowNum + $skipRow,
                    $val
                );
                ++$colNum;
            }
            ++$rowNum;
        }
        \PHPExcel_IOFactory::createWriter( $objPHPExcel, 'Excel2007' )->save( $file );
    }


    /**
     * 导出Excel -- 例子
     * @param $data ->二维数组
     */
    function put_excel( $filename, $data )
    {//导出Excel
        header( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' );
        header( 'Content-Disposition: attachment;filename=' . $filename . '.xlsx' );
        header( 'Cache-Control: max-age=0' );
        # 默认跳过第一行表头
        $this->putExcel( 'php://output', $data );
        exit();
    }
}
